/*
 * Copyright (c) 2002-2003 by OpenSymphony
 * All rights reserved.
 */
package org.jackysoft.opensymphony.workflow.entity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Element;
import org.jackysoft.util.ValidationUtils;


/**
 * Date: May 12, 2004
 * Time: 9:04:25 AM
 *
 * 
 */


public class ConditionsDescriptor extends AbstractDescriptor implements Validatable {
    /**
	 * 
	 */
	private static final long serialVersionUID = 6622703641008100879L;
	//~ Instance fields ////////////////////////////////////////////////////////

    private List conditions = new ArrayList();
    private String type;

    //~ Constructors ///////////////////////////////////////////////////////////

    /**
     * 
     */
   public  ConditionsDescriptor() { }

   
    public ConditionsDescriptor(org.dom4j.Element element) {
    	super(element);
    	this.init(element);
    }

    //~ Methods ////////////////////////////////////////////////////////////////

    public void setConditions(List conditions) {
        this.conditions = conditions;
    }

    
    
    
    
    
    public List getConditions() {
        return conditions;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getType() {
        return type;
    }

    public void validate() throws InvalidWorkflowDescriptorException {
        ValidationUtils.validate(conditions);

        if (conditions.size() == 0) {
            AbstractDescriptor desc = getParent();

            if ((desc != null) && (desc instanceof ConditionalResultDescriptor)) {
                throw new InvalidWorkflowDescriptorException("Conditional result from " + ((ActionDescriptor) desc.getParent()).getName() + " to " + ((ConditionalResultDescriptor) desc).getDestination() + " must have at least one condition");
            }
        }

        if ((conditions.size() > 1) && (type == null)) {
            throw new InvalidWorkflowDescriptorException("Conditions must have AND or OR type specified");
        }
    }


	@Override
	protected void init(org.dom4j.Element element) {
		conditions = new ArrayList();
		type = element.attributeValue("type");
		
		Iterator itr  =	element.elementIterator("condition");
	    
		for(;itr.hasNext();){
			org.dom4j.Element ce = (Element) itr.next();
			ConditionDescriptor condition = new ConditionDescriptor(ce);
			conditions.add(condition);
	    }   
		
	}
}
